package com.techjava.springboothystrixdemo.hystrix.services.impl;

import com.netflix.hystrix.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

@Service
public class ProductCommand extends HystrixCommand<String> {
 
    public ProductCommand() {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("demo"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("productCommand"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("productThreadPool"))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                    .withCoreSize(10)
                    .withMaxQueueSize(2)
                        .withQueueSizeRejectionThreshold(5))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()//
                    .withExecutionTimeoutInMilliseconds(1500))
        );
    }
 
    @GetMapping("/product")
    @Override
    protected String run() throws Exception {
        System.out.println("开始查询商品库存");
        return ProductService.queryByProductId();
    }
 
    @Override
    protected String getFallback() {
        if (this.circuitBreaker.isOpen()) {
            System.out.println("熔断器处于开启状态");
        } else {
            System.out.println("熔断器处于关闭状态");
        }
        return "====商品库存查询失败，我是降级方法====";
    }
}